import os

py_path = os.path.abspath(__file__)
proto_path = os.path.join(os.path.dirname(os.path.dirname(py_path)), 'proto')
msg_path = os.path.join(os.path.dirname(os.path.dirname(py_path)), 'none_bot_py_plugins', 'net', 'mod_msg.py')

proto_file = {}


def scan_file(file_name, path):
    f = open(path, 'r', encoding='utf-8')
    global proto_file
    proto_src = {}
    for line in f.readlines():
        if line.startswith("// "):
            proto_info = line.split()
            proto_src[proto_info[2]] = proto_info[1]
    f.close()
    proto_file[file_name] = proto_src


def make_py():
    text = []
    global proto_file
    text.append(u"# c2s proto class switch proto name")
    text.append(u"c2s_mod2msg = {")
    for k,v in proto_file.items():
        class_name = u"%s_pb2" % k
        for k2, v2 in v.items():
            if k2.startswith("c2s"):
                line = u'    "%s.%s": %s,' % (class_name, k2, v2)
                text.append(line)
    text.append(u"}")
    text.append(u"c2s_msg2mod = {")
    for k,v in proto_file.items():
        class_name = u"%s_pb2" % k
        for k2, v2 in v.items():
            if k2.startswith("c2s"):
                line = u'    %s: "%s.%s",' % (v2, class_name, k2)
                text.append(line)
    text.append(u"}")
    text.append(u"\n\n# s2c proto class switch proto num")
    text.append(u"s2c_mod2msg = {")
    for k,v in proto_file.items():
        class_name = u"%s_pb2" % k
        for k2, v2 in v.items():
            if k2.startswith("s2c"):
                line = u'    "%s.%s": %s,' % (class_name, k2, v2)
                text.append(line)
    text.append(u"}")
    text.append(u"s2c_msg2mod = {")
    for k,v in proto_file.items():
        class_name = u"%s_pb2" % k
        for k2, v2 in v.items():
            if k2.startswith("s2c"):
                line = u'    %s: "%s.%s",' % (v2, class_name, k2)
                text.append(line)
    text.append(u"}\n")
    with open(msg_path, 'w', encoding='utf-8') as fp:
        fp.write("\n".join(text))
        fp.close()


print(py_path)
print(proto_path)
print(msg_path)
for root, dirs, files in os.walk(proto_path):
    for name in files:
        top_name, extra = os.path.splitext(name)
        if extra == '.proto':
            scan_file(top_name, os.path.join(proto_path, name))
make_py()

